package com.example.flower_shop.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.io.File;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
        private static final Logger logger = LoggerFactory.getLogger(WebMvcConfig.class);

        @Value("${upload.path}")
        private String uploadPath;

        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
                // 上传文件访问路径
                String uploadDirectory = new File(uploadPath).getAbsolutePath();
                if (!uploadDirectory.endsWith(File.separator)) {
                        uploadDirectory = uploadDirectory + File.separator;
                }
                logger.info("配置上传文件访问路径: {}", uploadDirectory);
                registry.addResourceHandler("/uploads/images/**")
                                .addResourceLocations("file:" + uploadDirectory)
                                .setCachePeriod(3600)
                                .resourceChain(true);

                // 小程序静态资源
                logger.info("配置小程序静态资源路径");
                registry.addResourceHandler("/static/**", "/images/**")
                                .addResourceLocations("classpath:/static/", "classpath:/static/images/")
                                .setCachePeriod(3600)
                                .resourceChain(true);

                // Swagger UI资源
                registry.addResourceHandler("swagger-ui.html")
                                .addResourceLocations("classpath:/META-INF/resources/");
                registry.addResourceHandler("/webjars/**")
                                .addResourceLocations("classpath:/META-INF/resources/webjars/");
        }

        @Override
        public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                                .allowedOrigins("*")
                                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                                .allowedHeaders("*")
                                .maxAge(3600);
        }
}